package com.han.nettytestdemo.connector.netty;

import com.han.nettytestdemo.connector.netty.hc.NettyHCClient;
import com.han.nettytestdemo.connector.netty.intf.ConnectHCClientCallback;
import com.han.nettytestdemo.connector.netty.intf.MessageHcClientCallback;

import io.netty.channel.Channel;

public class NettyHcUtil {

    private volatile static NettyHcUtil instance = null;
    private NettyHCClient client;

    public static NettyHcUtil getInstance() {
        if (instance == null) {
            synchronized (NettyHcUtil.class) {
                if (instance == null) {
                    instance = new NettyHcUtil();
                }
            }
        }
        return instance;
    }

    /**
     * Netty连接
     *
     * @param connectClientCallback
     */
    public void nettyConnect(String ip, int port, final ConnectHCClientCallback connectClientCallback) {
        client = NettyHCClient.getInstance();
        client.setIPAndPort(ip, port);
        client.connectNetty();
        client.setConnectClientCallback(connectClientCallback);
    }

    /**
     * 向后台发送数据
     *
     * @param data
     */
    public void setNettyPost(String data) {
        try {
            Channel channel = NettyHCClient.getChannel();
            if (channel == null) {
//                Toast.makeText(this, "请先连接TCP服", Toast.LENGTH_SHORT).show();
            } else {
                channel.writeAndFlush(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 后台数据监听
     *
     * @param messageClientCallback
     */
    public void setMessageClientCallback(MessageHcClientCallback messageClientCallback) {
        try {
            if (client != null) {
                client.setMessageHcClientCallback(messageClientCallback);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 断开连接
     */
    public void destroy() {
        if (client != null) {
            client.destroy();
        }
    }
}
